<?php

class My_Controller_Plugin_RememberLogin extends Zend_Controller_Plugin_Abstract
{
    
    public function __construct()
    {
    }

    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        if (is_null(Zend_Auth::getInstance()->getIdentity()) )
        {
            $user = $this->getUserFromCookie();
            if ($user instanceof Application_Model_Usuario)
            {
                $authManager = Application_Model_AuthManager::getInstance();
                $estaAcreditado = $authManager->authorizedUser($user->getUsuario(), $user->getClave());
                if (true == $estaAcreditado)
                {
                    // Cookie and redirect
                    @setcookie('rememberLogin-user', $user->getUsuario(), time()+3600, 'localhost');
                    @setcookie('rememberLogin-hash', md5($user->getClave()), time()+3600, 'localhost');
                    My_Logger::getInstance()->info('Auto-login (using cookie "rememberLogin-*")');
                }
            }  
        }
    }
    
    /**
     * @param Zend_Controller_Request_Http $request
     * @return null | Application_Model_Usuario
     */
    protected function getUserFromCookie()
    {
        $returnValue = null;
        $request = $this->getRequest();
        /* @var $request Zend_Controller_Request_Http */
        $userName = $request->getCookie('rememberLogin-user', null);
        $hash = $request->getCookie('rememberLogin-hash', null);
        if (!is_null($userName) && !is_null($hash))
        {
            $result = Application_Model_Usuario_Finder::factory()->usuario($userName)->limit(1)->setReturnType('Application_Model_Usuario')->find();
            if ($result->count()>0)
            {
                $user = $result->current();
                /* @var $user Application_Model_Usuario */
                if (md5($user->getClave()) == $hash)
                {
                    My_Logger::getInstance()->info('Valid data in cookie "rememberLogin-*".');
                    $returnValue = $user;
                }
            }
        }        
        return $returnValue;
    }
}